import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

interface REquest_Interceptors {
  // 请求拦截
  requestInterceptors: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorsCatch: (err: any) => any
  // 响应拦截
  responseInterceptors: (config: AxiosResponse) => AxiosResponse
  responseInterceptorsCatch: (err: any) => any
}

interface Cherry_RequestConfig extends AxiosRequestConfig {
  interceptors?: REquest_Interceptors
}

class REQUEST {
  instance: AxiosInstance
  interceptors: REquest_Interceptors // 拦截器的类型

  constructor(config: Cherry_RequestConfig) { // 传进来的参数类型
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    // 注入请求拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorsCatch
    ) 
    // 注入响应拦截
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptors,
      this.interceptors?.responseInterceptorsCatch
      ) 
  }

  // 网络请求
  request(config: AxiosRequestConfig): void {
    this.instance.request(config).then(res => {
      console.log(res);
    })
  }
}


const service = new REQUEST({
  baseURL: '',
  timeout: 5000,
  interceptors: {
    requestInterceptors : (config) =>{
      return config
    },
    requestInterceptorsCatch: (err) =>{
      return err
    },
    responseInterceptors : (res) =>{
      return res
    },
    responseInterceptorsCatch: (err) =>{
      return err
    },
  }
})
export default service